﻿using Microsoft.Extensions.Logging;
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Wicture.DbRESTFul;
using Wicture.EPC.OnlineQueryProxy.Core;
using Wicture.EPC.OnlineQueryProxy.Models.Business;
using Wicture.EPC.OnlineQueryProxy.Models.Business.ES;
using Wicture.EPC.OnlineQueryProxy.Models.ES;
using Wicture.EPC.OnlineQueryProxy.Services.ES;

namespace Wicture.EPC.OnlineQueryProxy.Services
{
    public class PartEsService
    {
        private IESSearchService _eSSearchService;
        public PartEsService(IESSearchService eSSearchService)
        {
            _eSSearchService = eSSearchService;
        }

        public List<ESPartInfo> PartsSearch(BaseStockInfo stockInfo)
        {
            List<ESPartInfo> result = new List<ESPartInfo>();

            ESQueryRequest queryRequest = new ESQueryRequest();
            //查询条件
            List<QueryContainer> qcs = SearchPartQuery(stockInfo);
            if (qcs != null)
            {
                queryRequest.QueryContainer = new BoolQuery { Must = qcs };
                queryRequest.Indexs = new IndexName[] { AppConfig.PartIndex };
                queryRequest.Types = new TypeName[] { AppConst.PartType };
                var partEsInfo = GetSearchResponse(queryRequest);

                result = partEsInfo.PartList;
            }

            return result;
        }

        private List<QueryContainer> SearchPartQuery(BaseStockInfo stockInfo)
        {
            List<QueryContainer> qcs = new List<QueryContainer>();
            if (stockInfo != null)
            {
                if (!string.IsNullOrEmpty(stockInfo.partCode))
                {
                    qcs.Add(new TermQuery { Field = EsFieldConst.partCode, Value = stockInfo.partCode });
                }
                if (!string.IsNullOrEmpty(stockInfo.brandCode))
                {
                    qcs.Add(new TermQuery { Field = EsFieldConst.brandCode, Value = stockInfo.brandCode });
                }
                if (!string.IsNullOrEmpty(stockInfo.marketCode))
                {
                    qcs.Add(new TermQuery { Field = EsFieldConst.marketCode, Value = stockInfo.marketCode });
                }
            }
            return qcs;
        }

        /// <summary>
        /// 执行查询
        /// </summary>
        /// <param name="queryRequest"></param>
        /// <returns></returns>
        public EsPartResInfo GetSearchResponse(ESQueryRequest queryRequest)
        {
            EsPartResInfo result = new EsPartResInfo();
            ISearchResponse<ESPartInfo> response = _eSSearchService.Search<ESPartInfo>(queryRequest).Result;
            List<ESPartInfo> parts = null;
            if (response != null && response.Hits.Count() > 0)
            {
                parts = new List<ESPartInfo>();
                response.Hits.ToList().ForEach((i =>
                {
                    i.Source.id = i.Id;
                    parts.Add(i.Source);
                }));
            }
            result.PartList = parts;
            return result;
        }


        /// <summary>
        /// 批量导入
        /// </summary>
        /// <typeparam name="T">实体</typeparam>
        /// <param name="ts">需要导入的实体列表</param>
        /// <param name="indexName">索引名称</param>
        /// <param name="typeName">类型名称</param>
        /// <returns></returns>
        public async Task<bool> IndexBulk<T>(List<T> ts) where T : class
        {
            bool result = false;
            if (ts != null && ts.Count > 0)
            {
                IBulkResponse response = await ESUtil.IndexBulk<T>(ts, AppConfig.PartIndex, AppConst.PartType);
                if (response != null)
                {
                    if (response.ServerError != null)
                    {
                        LoggerManager.Logger.LogError(new Exception(response.ServerError.Error.ToString()), $"索引{AppConfig.PartIndex},IndexBulk失败");
                    }
                    else
                    {
                        result = true;
                    }
                }
                else
                {
                    LoggerManager.Logger.LogInformation("IndexBulk response is null");
                }
            }
            return result;
        }
    }
}
